package com.kly.cashmall.framework.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;


import com.kly.cashmall.framework.manager.IBroadcastManager;

import java.util.ArrayList;
import java.util.List;


public abstract class AbstractManagerActivity extends AbstractSupportActivity {

  private List<ServiceConnection> connectionList = null;
  private List<BroadcastReceiver> mReceiverList = null;

  /**
   * 统一管理Service
   */
  public void bindService(Class<?> clazz, ServiceConnection serviceConnection) {
    bindService(new Intent(this, clazz), serviceConnection, BIND_AUTO_CREATE);
    if (connectionList == null) {
      connectionList = new ArrayList<>();
    }
    connectionList.add(serviceConnection);
  }

  /**
   * 作用：
   * 1. 保证 BroadcastReceiver的注册和销毁配对
   * 2. 使用 此方法是强制使用LocalBroadcastManager 发送广播
   *
   * 不足：
   * 1. 需要确保同名Action不同时使用此方法和activity原生方法在同一个activity使用，否则会有问题
   */
  public void registerReceiver(final BroadcastReceiver receiver, final String... filters) {
    final IntentFilter filter = new IntentFilter();
    for (String f : filters) {
      filter.addAction(f);
    }
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
      @Override public void onReceive(final Context context, final Intent intent) {
        runOnUiThread(new Runnable() {
          @Override public void run() {
            if (!isDestroyed() && !isFinishing() && receiver != null) {
              receiver.onReceive(context, intent);
            }
          }
        });
      }
    };
    IBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter);
    if (mReceiverList == null) {
      mReceiverList = new ArrayList<>();
    }
    mReceiverList.add(broadcastReceiver);
  }

  @Override public void sendBroadcast(Intent intent) {
    //返回值表示，是否使用LocalBroadcastManager发送了广播，如果没有就使用原生广播
    if (!IBroadcastManager.getInstance(this).sendBroadcast(intent)) {
      super.sendBroadcast(intent);
    }
  }

  @Override public void unregisterReceiver(BroadcastReceiver receiver) {
    if (mReceiverList != null && mReceiverList.contains(receiver)) {
      IBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    } else {
      super.unregisterReceiver(receiver);
    }
  }

  private boolean clearFlag = false;

  @Override public void onBackPressed() {
    if (!interceptBack()) {
      super.onBackPressed();
    }
  }
  public boolean interceptBack() {
    return false;
  }
  /**
   * 页面销毁清理必要的数据
   */
  private void clearData() {
    if (clearFlag) {
      return;
    }
    clearFlag = true;

    if (connectionList != null && connectionList.size() > 0) {
      for (ServiceConnection connection : connectionList) {
        super.unbindService(connection);
      }
      connectionList.clear();
    }
    connectionList = null;

    if (mReceiverList != null && mReceiverList.size() > 0) {
      for (BroadcastReceiver br : mReceiverList) {
        this.unregisterReceiver(br);
      }
      mReceiverList.clear();
    }
    mReceiverList = null;

    willDestroy();
  }

  protected abstract void willDestroy();

  @Override protected void onResume() {
    super.onResume();
  }

  @Override protected void onPause() {
    super.onPause();
    if (isFinishing()) {
      clearData();
    }
  }

  @Override protected void onDestroy() {
    clearData();
    super.onDestroy();
  }
}
